var search = document.querySelector('.search');
var suggestions = document.querySelector('.suggestions')
let x = 1;
let url = "https://gist.githubusercontent.com/soyaine/81399bb2b24ca1bb5313e1985533c640/raw/bdf7df2cbcf70706c4a5e51a7dfb8c933ed78878/TangPoetry.json"
search.oninput = function() {
    var value = this.value;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText);
            console.log(data)
            var res = filter(value, data)
            setDOM(res)
        }
    }
}

function setDOM(data) {
    var html = '';
    // ES6箭头函数
    // data.forEach(element => {
    //     var str = `<li>
    // <p class="poet">${element.detail_text}</p>
    // <p class="title">${element.title} - ${element.detail_author[0]}(${element.detail_dynasty})</p>
    // </li>`
    //     html += str
    // });

    data.forEach(function(element) {
        var str = `<li>
    <p class="poet">${element.detail_text}</p>
    <p class="title">${element.title} - ${element.detail_author[0]}(${element.detail_dynasty})</p>
    </li>`
        html += str
    });
    suggestions.innerHTML = html

}

function filter(word, data) {
    var poets = [];
    data.forEach(function(el) {
        //判断在内容里面是否包含关键词
        var textFlag = el.detail_text.includes(word);
        //判断标题是否包含
        var titleFlag = el.title.includes(word);
        //判断作者是否包含关键字，作者必须有，且包含该关键词
        var authorFlag = el.detail_author[0] && el.detail_author[0].includes(word);
        //把满足条件的古诗放入poets数组
        if (textFlag || titleFlag || authorFlag) {
            poets.push(el)
        }
    })
    return poets

}